﻿namespace Tombstoner
{
    using System.Collections.Generic;
    using System.Reflection;
    using System.Windows;

    using Funq;

    using GalaSoft.MvvmLight.Messaging;

    using Tombstoner.ViewModel;

    using WP7Contrib.Common;
    using WP7Contrib.Logging;
    using WP7Contrib.Messaging;
    using WP7Contrib.Services.Navigation;
    using WP7Contrib.Services.Storage;

    public class BootStrapper
    {
        #region Constants and Fields

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="BootStrapper"/> class.
        /// </summary>
        public BootStrapper()
        {
            this.Container = new Container();

            this.ConfigureContainer();
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets Container.
        /// </summary>
        public Container Container { get; private set; }

        #endregion

        #region Implemented Interfaces

        #region IDisposable

        /// <summary>
        /// The dispose.
        /// </summary>
        public void Dispose()
        {
            if (this.Container != null)
            {
                this.Container.Dispose();
                this.Container = null;
            }
        }

        #endregion

        #endregion

        #region Methods

        private void ConfigureContainer()
        {
            this.Container.Register<ILogManager>(c => new LoggingService("Tombstoner"));
            this.Container.Register<ILog>(c => this.Container.Resolve<ILogManager>());

            var logManager = this.Container.Resolve<ILogManager>();
            logManager.Enable();

            this.Container.Register<INavigationService>(c => new ApplicationFrameNavigationService(((App)Application.Current).RootFrame));
            this.Container.Register<IMessenger>(c => new LastMessageReplayMessenger());
            var assemblies = new List<Assembly> { this.GetType().Assembly, typeof(BaseModel).Assembly };
            this.Container.Register<IStorageService>(c => new StorageService(assemblies, c.Resolve<ILog>()));

            this.Container.Register(
                c =>
                new MainViewModel(
                    c.Resolve<INavigationService>(),
                    c.Resolve<IMessenger>(),
                    c.Resolve<IStorageService>(),
                    c.Resolve<ILog>()));
        }

        #endregion
    }
}